import os
import codecs
import re

def get_msg_size(s):
	s = s.replace("{", "")
	s = s.replace("}", "")
	s = s.replace("0x", "")
	s = s.replace(",", "")
	return len(s)/2

def xor(key,msg):
	msg += '\x00'  #加上字符串终止符
	xor_msg = '{'
	for i in msg:
		xor_msg += hex(key ^ ord(i))
		xor_msg += ","
	xor_msg += "}"
	size = get_msg_size(xor_msg)
	return xor_msg, int(size)



def deal_file(filename, key):
	fp = open(filename)
	lines = fp.readlines()
	count = 0
	content = ""
	fp.close()
	os.rename(filename, filename + ".bak")  

	for line in lines:
		if line.startswith("#include"):
			content += line
			continue
		matchs = re.findall('"(.*?)"', line)
		print("matchs:{}".format(matchs))
		for m in matchs:
			handle = ''
			if '\\' in m:
				handle = m.replace("\\\\", "\\")
			else:
				handle = m

			print(handle)

			msg, size = xor(key ,handle)  #异或加密内容

			tmp = "char a{}[]={};\n".format(count, msg,count)
			tmp += "xor(a{}, {}, {});\n".format(count, size,key)
			tmp += line.replace('"{}"'.format(m), "a{}".format(count))
			line = tmp + "\n"
			count += 1

		content += line
	with open(filename, "w") as fp:
		fp.write(content)
	print(content)



if __name__ == '__main__':
	deal_file('./machineid.h', 0x86)


	